<?php

namespace App\Services;

use GuzzleHttp\Client as HttpClient;
use Illuminate\Support\Facades\Log;
use Tectalic\OpenAi\Authentication;
use Tectalic\OpenAi\Client as OpenAiClient;
use Tectalic\OpenAi\Models\ChatCompletions\CreateRequest;

class OpenAIService
{
    /**
     * @throws \Tectalic\OpenAi\ClientException
     * @throws \Exception
     */
    static public function chat($message, $model)
    {
        $auth = new Authentication(config('app.openai_api_key'));
        $httpClient = new HttpClient();
        $chatClient = new OpenAiClient($httpClient, $auth, config('app.openai_api_uri'));
        $request = new CreateRequest(['model' => $model, 'messages' => $message]);
        $response = $chatClient->chatCompletions()->create($request)->toModel();
        // Log::info(json_encode($response));
        if (isset($response->choices[0])) {
            // Log::info($response->choices[0]->message->content);
            return $response->choices[0]->message->content;
        } else {
            $message = "openai response choices error";
            Log::error($message);
            throw new Exception($message);
        }
    }
}
